//一对一的生产和消费
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

// 假设有一个缓冲区
int buffer = 0;
int data_available = 0;

void* producer(void* arg) {
    for (int i = 0; i < 5; i++) {
        pthread_mutex_lock(&mutex);
        while (data_available) { // 如果数据尚未被消费，等待
            pthread_cond_wait(&cond, &mutex);
        }
        buffer = i; // 生产数据
        data_available = 1;
        printf("Produced: %d\n", buffer);
        pthread_cond_signal(&cond); // 通知消费者数据已经生产
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

void* consumer(void* arg) {
    // int i = 5; // 假设消费5次
    while (1) {
        pthread_mutex_lock(&mutex);
        while (!data_available) // 等待数据可用
            pthread_cond_wait(&cond, &mutex);
        printf("Consumed: %d\n", buffer); //consumer在被唤醒后，必须重新获取锁（mutex）才能继续执行。
        if (buffer >= 4) { // 假设当生产者生产到4时结束
            pthread_mutex_unlock(&mutex);
            break;
        }
        data_available = 0;
        pthread_cond_signal(&cond); // 通知生产者可以继续生产
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main() {
    pthread_t tid1, tid2;

    pthread_create(&tid1, NULL, producer, NULL);
    pthread_create(&tid2, NULL, consumer, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}
